<?php
namespace app\common\model\food;

use app\common\model\BaseModel;
use think\facade\Cache;
use hema\wechat\Driver as Wechat;

/**
 * 配置模型 - 智慧餐厅
 */
class Setting extends BaseModel
{
    // 定义表名
    protected $name = 'setting';
    protected $createTime = false;

    // 追加字段
    protected $append = [];

    /**
     * 设置项描述
     */
    private $describe = [
        'mode' => '功能设置',
        'wxapptpl' => '微信小程序订阅消息',
        'wechattpl' => '微信公众号模板消息',
        'trade' => '交易设置',
        'recharge' => '充值设置',
        'delivery' => '配送设置',
        'pactsort' => '预约排队设置',
        'pacttable' => '预约订桌设置',
        'grade' => '等级管理',
        'other' => '其它设置',
    ];

    /**
     * 获取器: 转义数组格式
     */
    public function getValuesAttr($value)
    {
        return json_decode($value, true);
    }

    /**
     * 修改器: 转义成json格式
     */
    public function setValuesAttr($value)
    {
        return json_encode($value);
    }

    /**
     * 获取指定项设置
     */
    public static function getItem(string $key, $applet_id = null)
    {
        $data = self::getAll($applet_id);
        return isset($data[$key]) ? $data[$key]['values'] : [];
    }

    /**
     * 获取设置项信息
     */
    public static function detail(string $key,$applet_id = null)
    {
        is_null($applet_id) && $applet_id = self::$applet_id;
        $filter = [];// 筛选条件
        $filter['key'] = $key;
        $filter['applet_id'] = $applet_id;
        return self::withoutGlobalScope()->where($filter)->find();
    }

    /**
     * 全局缓存: 系统设置
     */
    public static function getAll($applet_id = null)
    {
        $self = new static;
        is_null($applet_id) && $applet_id = $self::$applet_id;
        $filter = [];// 筛选条件
        $filter['applet_id'] = $applet_id;
        if (!$data = Cache::get('food_setting_' . $applet_id)) {
            $data = array_column($self::withoutGlobalScope()->where($filter)->select()->toArray(), null, 'key');
            Cache::set('food_setting_' . $applet_id, $data);
        }
        return array_merge_multiple($self->defaultData(), $data);
    }

    /**
     * 更新系统设置
     */
    public function edit(string $key, array $values, $applet_id = null)
    {
        is_null($applet_id) && $applet_id = self::$applet_id;
        //如果是设置微信小程序订阅消息
        if($key == 'wxapptpl'){
            if(!$values = $this->wxapptpl($values,$applet_id)){
                $this->error = '未添加餐饮服务场所类目或类目未通过审核';
                return false;
            }
        }
        $model = self::detail($key,$applet_id) ?: $this;
        Cache::delete('food_setting_' . $applet_id);// 删除系统设置缓存
        return $model->save([
            'key' => $key,
            'describe' => $this->describe[$key],
            'values' => $values,
            'applet_id' => $applet_id,
        ]) !== false;
    }

    /**
     * 餐饮微信订阅消息设置
     */
    private function wxapptpl(array $values,$applet_id)
    {
        //验证是否添加小程序餐饮服务目录
        $wx = new Wechat;
        //获取已设置的服务类目
        $result = $wx->getCategory($applet_id);
        $isSet = false;//是否符合设置要求
        if($result['errcode']==0){
            foreach ($result['categories'] as $item){
                if($item['first']==220 AND $item['second']==632 AND $item['audit_status']==3){
                    $isSet = true;
                }
            }
        }
        if(!$isSet){
            $this->error = '未添加餐饮服务场所类目或类目未通过审核';
            return false;
        }
        //获取帐号下的模板列表
        if(!$result = $wx->getTemplateTpl($applet_id)){
            $this->error = $wx->getError();
            return false;
        }
        //循环删除订阅消息模板
        for($n=0;$n<sizeof($result['data']);$n++){
            if(!$wx->delTemplateTpl($applet_id,$result['data'][$n]['priTmplId'])){
                $this->error = $wx->getError();
                return false;
            }
        }
        //添加商家接单通知
        $tid = '7942';
        $kidlist = [2,6,7,10,5];
        $desc ='商家接单通知';
        if(!$result = $wx->addTemplateTpl($applet_id,$tid,$kidlist,$desc)){
            $this->error = $wx->getError();
            return false;
        }
        $values['receive'] = $result['priTmplId'];
        //添加骑手取货通知
        $tid = '8927';
        $kidlist = [1,2,4];
        $desc ='骑手取货通知';
        if(!$result = $wx->addTemplateTpl($applet_id,$tid,$kidlist,$desc)){
            $this->error = $wx->getError();
            return false;
        }
        $values['horseman'] = $result['priTmplId'];
        //添加订单完成通知
        $tid = '677';
        $kidlist = [13,11,14,12,5];
        $desc ='订单完成通知';
        if(!$result = $wx->addTemplateTpl($applet_id,$tid,$kidlist,$desc)){
            $this->error = $wx->getError();
            return false;
        }
        $values['finish'] = $result['priTmplId'];
        //添加取餐提醒
        $tid = '250';
        $kidlist = [23,12,30,16,7];
        $desc ='取餐提醒';
        if(!$result = $wx->addTemplateTpl($applet_id,$tid,$kidlist,$desc)){
            $this->error = $wx->getError();
            return false;
        }
        $values['take'] = $result['priTmplId'];
        //添加订单配送通知
        $tid = '584';
        $kidlist = [1,2,15,4,5];
        $desc ='订单配送通知';
        if(!$result = $wx->addTemplateTpl($applet_id,$tid,$kidlist,$desc)){
            $this->error = $wx->getError();
            return false;
        }
        $values['delivery'] = $result['priTmplId'];
        //退款状态通知
        $tid = '8995';
        $kidlist = [1,2,4,5];
        $desc ='退款状态通知';
        if(!$result = $wx->addTemplateTpl($applet_id,$tid,$kidlist,$desc)){
            $this->error = $wx->getError();
            return false;
        }
        $values['refund'] = $result['priTmplId'];
        return $values;
    }
    
   

    /**
     * 默认配置
     */
    public function defaultData()
    {
        return [
            'pactsort' => [
                'key' => 'pactsort',
                'describe' => '预约排队设置',
                'values' => [
                    'is_open' => 0,
                    'is_print' => 0,
                    'is_call' => 0,
                    'range' => 50,
                ],
            ],
            'pacttable' => [
                'key' => 'pacttable',
                'describe' => '预约订桌设置',
                'values' => [
                    'is_open' => 0,
                    'is_print' => 0,
                    'range' => 50,
                ],
            ],
            'grade' => [
                'key' => 'grade',
                'describe' => '等级设置设置',
                'values' => [
                    0 => [
                        'score' => 0 , 'gift' => []
                    ],
                    1 => [
                        'score' => 100 , 'gift' => []
                    ],
                    2 => [
                        'score' => 500 , 'gift' => []
                    ],
                    3 => [
                        'score' => 1000 , 'gift' => []
                    ],
                    4 => [
                        'score' => 3000 , 'gift' => []
                    ],
                    5 => [
                        'score' => 5000 , 'gift' => []
                    ],
                ],
            ],
            'trade' => [
                'key' => 'trade',
                'describe' => '交易设置',
                'values' => [
                    'order' => [
                        'time' => '10',//任务执行间隔
                        'close_time' => '60',//未支付订单关闭时间
                        'delivery_time' => '60',//已配送订单自动配送完成时间
                        'receive_time' => '60', //配送完毕订单用户自动确认收货时间 
                        'cmt_time' => '1440', //收货订单用户自动评价时间
                        'refund_time' => '0' //退款订单自动退款时间
                    ],
                    'freight_rule' => '10',
                ]
            ],
            'delivery' => [
                'key' => 'delivery',
                'describe' => '配送设置',
                'values' => [
                    'delivery_range' => '3000', //配送范围
                    'free_range' => '0',        //免费配送范围
                    'delivery_price' => '5',    //配送费用
                    'min_price' => '15',        //起送价格
                ]
            ],
            'other' => [
                'key' => 'other',
                'describe' => '其它设置',
                'values' => [
                    'bind_phone' => '1',//登录小程序是否强制用户绑定手机号
                    'order_export' => 'col', //订单导出样式 col竖排，row横排
                    'postpaid' => [0,0,0],//后付费设置
                    'staff_price' => '0',//员工折扣
                ]
            ],
            'wxapptpl' => [
                'key' => 'wxapptpl',
                'describe' => '微信小程序订阅消息',
                'values' => [
                    'receive' => '',//商家接单通知
                    'horseman' => '',//骑手取货通知
                    'delivery' => '',  //订单配送通知
                    'take' => '',  //取餐提醒
                    'finish' => '',  //订单完成通知
                    'refund' => '',  //退款状态通知
                ],
            ],
            'wechattpl' => [
                'key' => 'wechattpl',
                'describe' => '微信公众号模板消息',
                'values' => [
                    'receive' => '',//商家接单通知
                    'horseman' => '',//骑手取货通知
                    'delivery' => '',  //订单配送通知
                    'take' => '',  //取餐提醒
                    'finish' => '',  //订单完成通知
                    'refund' => '',  //退款状态通知
                ],
            ],
            'recharge' => [
                'key' => 'recharge',
                'describe' => '充值设置',
                'values' => [
                    'is_open' => 1,     //是否开启
                    'is_custom' => 1,   //是否允许用户自定义金额
                    'is_match_plan' => 1,   //是否自动匹配套餐
                    'describe' => '1. 账户充值仅限微信在线方式支付，充值金额实时到账；
2. 账户充值套餐赠送的金额即时到账；
3. 账户余额有效期：自充值日起至用完即止；
4. 若有其它疑问，可拨打客服电话400-000-1234', //充值说明
                ],
            ],
        ];
    }

}
